/*
 * Copyright 2012 JapakGIS Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * Author: david.japakgis@gmail.com(David Kimari)

*/
$(document).ready(function(){
	$('#searchTF').val("Type in where you live...")
	var styles = [
		{
		  featureType: "administrative",
		  stylers: [
			{ visibility: "off" }
		  ]
		},
		{
		  featureType: "poi.park",
		  stylers: [
			{ hue: "#d3f016" }
		  ]
		}
	  ];

	var mapOps = {
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		zoom:6,
		panControl: false,
		mapTypeControl:true,
		zoomControlOptions: {
			position: google.maps.ControlPosition.LEFT_CENTER
		},
		center: new google.maps.LatLng(0.173559, 37.90619300000003)
	}
	var map = new google.maps.Map(document.getElementById('voter-map'), mapOps)
	map.setOptions({styles: styles});
	var  places = new google.maps.places.PlacesService(map);
	var autocomplete  = new google.maps.places.AutocompleteService();
	var markerLayer = [];
	var mapCenter = new google.maps.LatLng(0.173559, 37.90619300000003)
	var selectedConstituency = [];
	var markerHTML = "";
	var selectedCounty =  []
	var userMarker = new google.maps.Marker({//The marker showing the users location
		icon: '../images/place.png'
	})
	var countyLayer = new Polyman({
		type: "county"
	});
	//configure the infoBox for layer mouseovers
	var myOptions = {
		disableAutoPan: true
		,maxWidth: 0
		,pixelOffset: new google.maps.Size(5, 10)
		,zIndex: null
		,boxStyle: {
		  opacity: 0.95
		 }
		,closeBoxURL: ""
		,infoBoxClearance: new google.maps.Size(1, 1)
		,isHidden: false
		,pane: "floatPane"
		,enableEventPropagation: false
	};
	var infoBox = new InfoBox(myOptions)
	
	//Configure the InfoWindow for Polling Stations
	var myops = {
		disableAutoPan: false
		,maxWidth: 0
		,pixelOffset: new google.maps.Size(2, -3)
		,zIndex: null
		,boxStyle: { 
		  opacity: 0.95
		 }
		,closeBoxURL: "../images/closeInfoWindow.png"
		,closeBoxMargin: "3px"
		,infoBoxClearance: new google.maps.Size(1, 1)
		,isHidden: false
		,pane: "floatPane"
		,enableEventPropagation: false
	};

	var psinfo = new InfoBox(myops)
	
	//configure the polygons within the county layer
	$.each(countyLayer.polyArray, function(i, val){
		val.setOptions({
			strokeColor: "#214813",
			strokeWeight: 2,
			strokeOpacity: 1,
			fillOpacity: 0.5,
			fillColor:"#46A24A"
		})
		google.maps.event.addListener(val,'click', function(event){
			countyClick(val.polyName);
			if(val.polyName=="MURANG'A"){
				$('#select-county').children('option:contains(MURANG)').attr('selected', true);
			}
			else{
				$('#select-county').children('option[value="'+val.polyName+'"]').attr('selected', true);
			}
			$('#suggestion-box').slideUp(100).empty()
		})
		
		google.maps.event.addListener(val,'dbclick', function(event){
			map.setZoom(map.getZoom()+1)
		})
		
		google.maps.event.addListener(val,'mouseover', function(event){
			infoBox.setContent('<div class="layer-window">'+val.polyName+' County</div>');
			if(selectedCounty.length > 0){
				if(selectedCounty[0] == val){
					val.setOptions({
						fillOpacity:0
					})
				}
				else{
					val.setOptions({
						fillOpacity:0.7,
						strokeWeight: 3,
						strokeColor:"#300"
					})
				}
			}
			else{
				val.setOptions({
					fillOpacity:0.7,
					strokeWeight: 3,
					strokeColor:"#300"
				})
			}
			infoBox.open(map)
		})
		google.maps.event.addListener(val, 'mousemove', function(event){
			infoBox.setPosition(event.latLng)
			
		})
		google.maps.event.addListener(val, 'mouseout', function(event){
			infoBox.close()
			if(selectedCounty.length > 0){
				if(selectedCounty[0] == val){
					val.setOptions({
						fillOpacity:0
					})
				}
				else{
					val.setOptions({
						fillOpacity:0.5,
						strokeWeight: 2,
						strokeColor:"#214813"
					})
				}
			}
			else{
				val.setOptions({
					fillOpacity:0.5,
					strokeWeight: 2,
					strokeColor:"#214813"
				})
			}
			
		})
	})
	
	var constituencyLayer = new Polyman({
		type: "constituency"
	});
	//configure the polygons within the constituency layer
	$.each(constituencyLayer.polyArray, function(i, val){
		val.setOptions({
			strokeColor: "#214813",
			strokeWeight: 1,
			strokeOpacity: 1,
			fillOpacity:0.1,
			fillColor: "#46A24A"
			
		})
		google.maps.event.addListener(val,'click', function(event){
			constituencyClick(val.polyName);
			$('#select-constituency').children('option[value="'+val.polyName+'"]').attr('selected', true);
			mapCenter = map.getCenter()
		})
		
		google.maps.event.addListener(val,'dbclick', function(event){
			map.setZoom(map.getZoom()+1)
		})
		
		google.maps.event.addListener(val,'mouseover', function(event){
			infoBox.setContent('<div class="layer-window">'+val.polyName+' Constituency</div>')
			infoBox.open(map)
			if(selectedConstituency.length > 0){
				if(selectedConstituency[0] == val){
					val.setOptions({
						fillOpacity: 0,
						fillColor:"#46A24A"
					})
				}
				else{
					val.setOptions({
						fillOpacity:0.3,
						fillColor:"#46A24A",
						strokeWeight: 2,
						strokeColor:"#300"
					})
				}
			}
			else{
				val.setOptions({
					fillOpacity:0.3,
					fillColor:"#46A24A",
					strokeWeight: 2,
					strokeColor:"#300"
				})
			}
		})
		google.maps.event.addListener(val, 'mousemove', function(event){
			infoBox.setPosition(event.latLng)
			if(selectedConstituency.length > 0){
				if(selectedConstituency[0] == val){
					infoBox.close()
				}
			}
		})
		google.maps.event.addListener(val, 'mouseout', function(event){
			infoBox.close()
			if(selectedConstituency.length > 0){
				if(selectedConstituency[0] == val){
					val.setOptions({
						fillOpacity: 0,
						fillColor:"#46A24A"
					})
				}
				else{
					val.setOptions({
						fillOpacity:0.1,
						strokeWeight: 1,
						strokeColor:"#214813"
					})
				}
			}
			else{
				val.setOptions({
					fillOpacity:0.1,
					strokeWeight: 1,
					strokeColor:"#214813"
				})
			}
		})
	})
	
	var showLayer = function(theLayer, feature, parent){//Functions that decides on the features of the Later to display
		$.each(theLayer.polyArray, function(i, val){
			if(feature){
				if(val.polyName == feature){
					val.setMap(map);
				}
				else{
					val.setMap(null)
				}
			}
			else if(parent){
				if(val.polyParent == parent){
					val.setMap(map);
				}
				else{
					val.setMap(null)
				}
			}
			else{
				val.setMap(map);
			}
		})
	}
	
	showLayer(countyLayer); //make the layer visible
	
	//functon to fetch List of counties to the select options
	var getCountyList = function(){
		$.ajax({
			url: "/county/",
			async: false,
			dataType: 'json',
			success: function(json){
				counties = json.results;
				$.each(counties, function(c, county){
					$option = $('<option value="'+county.name+'">'+county.name+'</option>');
					$('#select-county').append($option)
				})
			}
		})
		$('#select-county').change(function(){
			if($(this).children('option:selected').val()=="all"){
				clearMarkers();
				psinfo.close;
				map.setZoom(6);
				map.setCenter(new google.maps.LatLng(0.173559, 37.90619300000003))
				constituencyLayer.hide();
				countyLayer.setOptions({
						strokeColor: "#214813",
						strokeWeight:1,
						map:map,
						fillColor: "#46A24A",
						fillOpacity:0.5
					})
				$.each(selectedConstituency, function(a, sC){
					sC.setOptions({
						fillOpacity:0.2,
						fillColor: "#46A24A",
						strokeWeight: 1,
						strokeColor:"#214813"
					});
				});
				$('#select-constituency').attr('disabled', true).html('<option value="select">Select County First...</option>');
				$('#select-ward').attr('disabled', true).html('<option value="select">Select Constituency First...</option>');
			}
			else{
				countyClick($(this).children('option:selected').val());
			}
			
		})
	}
	getCountyList();//Load the county list
	
	//function that handles focus on a given layer feature
	var fitToFeature = function(feature, theLayer){
		$.each(theLayer.polyArray, function(i, val){
			if(val.polyName == feature){
				map.fitBounds(val.getBounds());
				if(theLayer.type == "county"){
					selectedCounty = []
					val.setOptions({
						map: null,
						fillOpacity:0,
						fillColor:"#fff"
					})
					selectedCounty.push(val)
				}
				else{
					selectedConstituency = []
					val.setOptions({
						strokeWeight:2,
						fillOpacity:0,
						strokeColor: "#300"
					})
					selectedConstituency.push(val);
				}
			}
			else{
				if(theLayer.type == "county"){
					val.setOptions({
						strokeColor: "#214813",
						map: map,
						strokeWeight:1,
						fillColor: "#46A24A",
						fillOpacity:0.5
					})
				}
				else{
					val.setOptions({
						strokeColor: "#214813",
						strokeWeight:1,
						fillColor:"#46A24A",
						fillOpacity:0.2
					})
				}
			}
		});
	}
	
	//function to handle all county clicks, on map or on drop down.
	var countyClick = function(cname){
		clearMarkers()
		psinfo.close();
		$.each(selectedConstituency, function(a, sC){
			sC.setOptions({
				fillOpacity:0.5,
				strokeWeight: 1,
				strokeColor:"#214813"
			});
		});
		$('#select-constituency').removeAttr('disabled').html('<option value="select">Loading Constituencies...</option>');
		$('#avail-ps-body').removeClass('maximized').addClass('minimized').empty();
		$.ajax({
			url: "/constituency/?county="+cname,
			async: true,
			dataType: 'json',
			success: function(json){
				$('#select-constituency').html('<option value="all">All Constituencies...</option>');
				constituencies = json.results;
				fitToFeature(cname, countyLayer)
				$.each(constituencies, function(c, constituency){
					showLayer(constituencyLayer, false, cname);//Display constituencies in the county
					$option = $('<option value="'+constituency.name+'">'+constituency.name+'</option>'); 
					$('#select-constituency').append($option)
				})
			}
		});
		$('#select-constituency').change(function(){
			if($(this).children('option:selected').val()=="all"){
				countyClick(cname);
				clearMarkers()
			}
			else{
				constituencyClick($(this).children('option:selected').val());
			}
			
		})
		
		$.each(countyLayer, function(i, val){
			if(val.polyName == cname){
				map.fitBounds(val.getBounds())
			}
		})
	}
	
	//function to handle all constituency clicks either from the map or dropdown list
	var constituencyClick = function(cname, userM){
		clearMarkers()
		psinfo.close();
		$('#select-ward').removeAttr('disabled').html('<option value="select">Loading Wards...</option>');
		
		$('#voting-info-body').slideUp(0);
		$('#avail-ps-body').removeClass('maximized').addClass('minimized');
		$('#voter-info-show-toggle').text("[show]")
		$.ajax({
			url: "/ward/?constituency="+cname,
			async: true,
			dataType: 'json',
			success: function(json){
				$('#select-ward').html('<option value="all">All Wards...</option>');
				fitToFeature(cname, constituencyLayer)
				wards = json.results;
				$.each(wards, function(c, ward){
					$option = $('<option value="'+ward.name+'">'+ward.name+'</option>')
					$('#select-ward').append($option)
				})
				$('#select-constituency').children('option[value="'+cname+'"]').attr('selected', true);
			}
		})
		
		if(userM){
			loadPollingStations(cname,"constituency",true);
		}
		else{
			loadPollingStations(cname,"constituency");
		}
		$('#select-ward').change(function(){//function for handling ward selection
			psinfo.close();
			if($(this).children('option:selected').val()=="all"){
				constituencyClick(cname)
			}
			else{
				$('#avail-ps-body').empty();
				loadPollingStations($(this).children('option:selected').val(),"ward");
			}
			
		});
		$.each(constituencyLayer, function(i, val){
			if(val.polyName == cname){
				map.fitBounds(val.getBounds())
			}
		})
	}
	
	//function used to load pollingstations to both the sideBar and the map
	var loadPollingStations = function(edname, ltype, userM){
		$('#avail-ps-body').html('<img src="../../images/loading.gif" align="center" />')
		if(ltype=="ward"){
			url = '/pollingstation/?ward='+edname
			$('#ps-title').text("Polling Stations in "+edname.toLowerCase().capitalize()+" Ward")
		}
		else if(ltype=="constituency"){
			url = '/pollingstation/?constituency='+edname;
			$('#ps-title').text("Polling Stations in "+edname.toLowerCase().capitalize()+" Constituency")
		}
		$.ajax({
			url: url,
			async: true,
			dataType: 'json',
			success: function(data){
				$('#avail-ps-body').empty();
				$('#avail-ps-body').addClass('maximized');
				clearMarkers()//clear markers
				pollingstations = data.results
				if(userM){
					userMarker.setMap(map)
				}
				if(pollingstations.length==0){
					$ps = $('<div class="ps-row"> No Polling Stations Found for '+edname+' '+ltype+'</div>');
					$('#avail-ps-body').append($ps);
				}
				$.each(pollingstations, function(p, pollingstation){
					
					if( pollingstation.point.lon > 0){
						var parentLayer = pollingStationWithin(pollingstation.constituency)
						var psPos = new google.maps.LatLng(pollingstation.point.lat, pollingstation.point.lon);
						if(parentLayer.containsLatLng(psPos)){
							var markerHTML = '<div id="infoBox"><div id="infoBox-header">Registration Center Information</div><div id="infoBox-body"><div id="tablewrap"><div class="tablewrap-component"><img src="../images/iebc.png" align="right" style="float:left;"/><br clear="all" /></div><div class="tablewrap-component"><div class="row"><div class="row-title">Location: </div><div class="row-content">'+pollingstation.name.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">County: </div><div class="row-content">'+pollingstation.county.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">Constituency: </div><div class="row-content">'+pollingstation.constituency.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">Ward: </div><div class="row-content">'+pollingstation.ward.toLowerCase().capitalize()+'</div></div></div><br clear="all" /></div><div id="tips-part"><ol style="clear:both" id="tipsOl"><li>You will need a valid Kenyan Passport or a National ID.</li><li> Remember to register where you will vote on March 4th.</li><li>Open from: 8a.m. - 5p.m.</li></ol></div></div></div>';
							
							$ps = $('<div class="ps-row hasgeo">'+pollingstation.name.toLowerCase().capitalize()+'</div>');
							var psMarker = new google.maps.Marker({
								position: psPos,
								map: map,
								icon: '../images/has-geo.png'
							})
							
							google.maps.event.addListener(psMarker, 'click', function(event){
								psMarker.setAnimation(null);
								psinfo.setContent(markerHTML)
								psinfo.open(map, psMarker)	
								$('#select-ward').children('option[value="'+pollingstation.ward+'"]').attr('selected', true);				
							})
							
							google.maps.event.addListener(psMarker, 'mouseover', function(event){
								infoBox.open(map, psMarker)
								infoBox.setContent('<div class="layer-window" style="font-weight:100; color:white; width:175px">'+pollingstation.name+' <br /><strong style="font-size:12px; font-weight:100; color:#fff">Click for details</strong></div>');
								infoBox.setPosition(event.latLng);
							})
							
							markerLayer.push(psMarker);
						}
						else{
							var markerHTML = '<div id="infoBox"><div id="infoBox-header">Registration Center Information</div><div id="infoBox-body"><div id="tablewrap"><div class="tablewrap-component"><img src="../images/iebc.png" align="right" style="float:left;"/><br clear="all" /></div><div class="tablewrap-component"><div class="row"><div class="row-title">Location: </div><div class="row-content">'+pollingstation.name.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">County: </div><div class="row-content">'+pollingstation.county.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">Constituency: </div><div class="row-content">'+pollingstation.constituency.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">Ward: </div><div class="row-content">'+pollingstation.ward.toLowerCase().capitalize()+'</div></div></div><br clear="all" /></div><div id="tips-part"><ol style="clear:both" id="tipsOl"><li>You will need a valid Kenyan Passport or a National ID.</li><li> Remember to register where you will vote on March 4th.</li><li>Open from: 8a.m. - 5p.m.</li><li class="nogeoInfo" style="color:#500">Sorry we could not map your Polling Station Location</li></ol></div></div></div>';
						
						$ps = $('<div class="ps-row nogeo">'+pollingstation.name.toLowerCase().capitalize()+'</div>');
						}
					}
					else{
						var markerHTML = '<div id="infoBox"><div id="infoBox-header">Registration Center Information</div><div id="infoBox-body"><div id="tablewrap"><div class="tablewrap-component"><img src="../images/iebc.png" align="right" style="float:left;"/><br clear="all" /></div><div class="tablewrap-component"><div class="row"><div class="row-title">Location: </div><div class="row-content">'+pollingstation.name.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">County: </div><div class="row-content">'+pollingstation.county.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">Constituency: </div><div class="row-content">'+pollingstation.constituency.toLowerCase().capitalize()+'</div></div><div class="row"><div class="row-title">Ward: </div><div class="row-content">'+pollingstation.ward.toLowerCase().capitalize()+'</div></div></div><br clear="all" /></div><div id="tips-part"><ol style="clear:both" id="tipsOl"><li>You will need a valid Kenyan Passport or a National ID.</li><li> Remember to register where you will vote on March 4th.</li><li>Open from: 8a.m. - 5p.m.</li><li class="nogeoInfo" style="color:#500">Sorry we could not map your Polling Station Location</li></ol></div></div></div>';
						
					$ps = $('<div class="ps-row nogeo">'+pollingstation.name.toLowerCase().capitalize()+'</div>');
					}
					
					$('#infoBox').mouseenter(function(){
						psinfo.close();
						alert("Here");
					})
					
					$ps.click(function(){
						if( pollingstation.point.lon > 0){
							if(parentLayer.containsLatLng(psPos)){
								map.setCenter(psPos);
								psMarker.setAnimation(google.maps.Animation.DROP);
								google.maps.event.addListener(map, 'click', function(event){
									stopMarkers()
								})
								psinfo.open(map, psMarker);
								psinfo.setContent(markerHTML);
								psinfo.setOptions({
									pixelOffset: new google.maps.Size(2, -3)
								});
							}
							else{
								psinfo.setPosition(map.getCenter());
								psinfo.setContent(markerHTML);
								psinfo.setOptions({
									pixelOffset: new google.maps.Size(-210, -3)
								});
								psinfo.open(map)
							}
						}
						else{
							psinfo.setPosition(map.getCenter());
							psinfo.setContent(markerHTML);
							psinfo.setOptions({
								pixelOffset: new google.maps.Size(-210, -3)
							});
							psinfo.open(map)
						}
						
						$('#select-ward').children('option[value="'+pollingstation.ward+'"]').attr('selected', true);
					})
					$('#avail-ps-body').append($ps)
				})
			}
		})
	}
	
	var stopMarkers = function(){//Function to stop marker bounce 
		if(markerLayer.length > 0){
			$.each(markerLayer, function(i, val){
				val.setAnimation(null);
			});
		}
	}
	
	var clearMarkers = function(){//Function to stop marker bounce 
		if(markerLayer.length > 0){
			$.each(markerLayer, function(i, val){
				val.setMap(null);
			});
		}
		userMarker.setMap(null);
		markerLayer = []
	}
	
	$('#searchTF').focusin(function(){//handles the behavior of the textfield when it gets focus
		if($(this).val()=="Type in where you live..."){
			$(this).val("")
		}
	})
	.focusout(function() {//handles the behaviour of the search textfield on focus out
        if($(this).val()=="" || $(this).val()==" "){
			$(this).val("Type in where you live...")
		}
    })
	.keyup(function(event){//handles the behaviour of the textfield once a key is pressed.
		var searchValue = $(this).val();
		$('#suggestion-box').slideDown(100);
        if(searchValue > 0 || searchValue!=" "){//if the value in the text field is not blank
			if(event.which==13){//Behavior if the key that was pressed is the Return Key
				var request = {
					query: searchValue+", Kenya"
				}
				userMarker.setTitle(searchValue)
				places.textSearch(request, getPlace);
			}
			else{//Behaviour if the key pressed is not the Return Key.
				var ops = {
				  componentRestrictions: {country: 'ke'},
				  input: searchValue
				}
				autocomplete.getPlacePredictions(ops, getSuggestion);
			}
		}
		else{ //if the value is blank
		}
    });
	
	var getSuggestion = function(predictions, status){//Suggest the possible areas that the user lives in from his/her suggestions
		if (status == google.maps.places.PlacesServiceStatus.OK) {//if a suggestion matching the user request is found
			$('#suggestion-box').empty();
			for (var i = 0, prediction; prediction = predictions[i]; i++) {
				$prediction = $('<div class="suggestion">' + prediction.description + '</div>');
				$prediction.click(function(){//function that handles gadget behavior on prediction click
					var request = {
						query: $(this).text()
					}
					userMarker.setTitle($(this).text())
					places.textSearch(request, getPlace);
					$('#searchTF').val($(this).text());
				})
				var elemNo = 1;
				$('#suggestion-box').append($prediction)
				$(document).keyup(function(event){
					if(event.which==38){
						if(elemNo >=0){
							$('.suggestion:nth-child('+elemNo+')').addClass('selected').siblings('.suggestion').removeClass('selected')
							elemNo+=1;
						}
					}
					else if(event.which==40){
						if(elemNo <= 1){
							$('.suggestion:nth-child('+elemNo+')').addClass('selected').siblings('.suggestion').removeClass('selected')
							elemNo-=1;
						}
					}
				})
			}
		}
		else{// if no match was found.
			$('#suggestion-box').slideDown(100).html("<div style='background-color:white; padding:2px 6px'>Sorry it seems that we could not find a place matching your request. Please enter another Location or use the map and form to find your area</div>");
		}
	}
	
	var getPlace = function(results, status){//Get the place the user lives in
		$('#suggestion-box').slideUp(100).empty()
		if (status == google.maps.places.PlacesServiceStatus.OK) {//If the Place was found
			var userLocation = results[0].geometry.location;
			userLivesIn(userLocation)
		}
		else{//if the place was not found
			$('#suggestion-box').slideDown(100).html("<div style='background-color:white; padding:2px 6px'>Sorry it seems that we could not find a place matching your request. Please enter another Location or use the map and form to find your area</div>");
		}
	}
	
	var userLivesIn = function(geoLocation){// this function is used to determine the users Location
		$.each(constituencyLayer.polyArray, function(i, val){
			if (val.containsLatLng(geoLocation)){//Get the users constituency
				countyClick(val.polyParent);
				constituencyClick(val.polyName, true);
				//$('#select-constituency').children('option[value="'+val.polyName+'"]').attr('selected', true);
				$('#select-county').children('option[value="'+val.polyParent+'"]').attr('selected', true);
				userMarker.setPosition(geoLocation);
			}
		})
	}
	
	var pollingStationWithin = function(constituency){ //ensure that the point falls within the polygon
		var there = 0;
		$.each(constituencyLayer.polyArray, function(i, val){
			if (val.polyName == constituency){//if the point is found and falls within the desired polygon
				there = val
			}
		})
		return there
	}
	$('#feedback-form-prompt').click(function(){
		$('#feedback-form').slideToggle(200);
	})
	
	$('#sendFeedback').click(function(){
		$.post("/",{message: $('#feedback-name').val()+"("+$('#feedback-email').val()+")<br /> "+$('#feedback-message').val()},function(data){
			var previousHTML = $('#feedback-form').html();
				$('#feedback-form').html("<div style='color:#451111; font-size:14px'>We thank you for your feedback.</div>");
			var feedBackTimer = setTimeout(function(){
				$('#feedback-form').hide(1000).html(previousHTML);
				clearTimeout(feedBackTimer);
			},2600)
		});
	});
	
	$('#get-gadget').click(function(){
		$('#embbed-instructions').slideToggle(200);
	});	
	
	var countdown = function(){
			var minutes=1000*60;
			var hours=minutes*60;
			var days=hours*24;
			var endday=new Date("December 19, 2012 00:00:00");
			endday = endday.getTime();
			var today = new Date();
			today = today.getTime();
			var remaining = endday - today
			$('#counter').html('Deadline (<span style="font-size:11px">18<sup>th</sup> December 2012</span>) : <strong>'+Math.round(remaining/days)+' days to go </strong>');
	}
	countdown()
	$('#voting-info-title').click(function() {
		if($('#voting-info-body').is(":hidden")){
			$('#voter-info-show-toggle').text("[hide]")
			$('#avail-ps-body').removeClass('maximized').addClass('minimized');
		}
		else{
			$('#voter-info-show-toggle').text("[show]")
			$('#avail-ps-body').removeClass('minimized').addClass('maximized');
		}
        $('#voting-info-body').slideToggle(200);
    });
	
	
});

$(document).click(function(){
	$('#suggestion-box').slideUp(0).empty()
})